package com.software.demo2;

import com.software.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Run {
    public static void main(String[] args) {
        Run run = new Run();
        run.save();
        //run.get();
        //run.edit();
    }
    public void save() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("hugx");
        userInfo.setPassword("hugx");

        PersonInfo personInfo = new PersonInfo();
        personInfo.setName("胡国欣");
        personInfo.setIdNumber("130124XXXXXXXXXXXX");

        userInfo.setPersonInfo(personInfo);
        personInfo.setUserInfo(userInfo);

        session.save(userInfo);

        transaction.commit();
        session.close();
    }
    public void get() {
        Session session = HibernateUtils.getSession();
        UserInfo userInfo = session.get(UserInfo.class, 1);

        System.out.println(userInfo.getUserName());
        System.out.println(userInfo.getPersonInfo().getIdNumber());

        session.close();
    }
    public void edit() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        // 修改先做查询
        UserInfo userInfo = session.get(UserInfo.class, 1);
        // !!!做修改操作时，不要修改主键的属性 id
        userInfo.setUserName("小胡胡");

        userInfo.getPersonInfo().setIdNumber("你猜");

        session.update(userInfo);
        transaction.commit();
        session.close();
    }
    // 删除方法自行写一下，注意，删除之前先进行查询，然后session.delete(obj)
}
